package com.hyt.it.ogt.kq.common.config.exception;

import com.hyt.core.exception.IFailMessage;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import org.apache.commons.lang3.StringUtils;

/**
 * 政企考务业务异常
 *
 * @author liuq
 */
public class KqException extends RuntimeException implements IFailMessage {

	private static final long serialVersionUID = 570288218815530666L;
	
	private int errCode;

    private String errMsg;

    private Object data;

    private Throwable causeThrowable;

    public KqException() {
    }

    public KqException(String errMsg) {
        super(errMsg);
        this.errMsg = errMsg;
    }

    public KqException(int errCode, String errMsg) {
        super(errMsg);
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    public KqException(int errCode, String errMsg, Object data) {
        super(errMsg);
        this.errCode = errCode;
        this.errMsg = errMsg;
        this.data = data;
    }

    public KqException(int errCode, Throwable throwable) {
        super(throwable);
        this.errCode = errCode;
        setCauseThrowable(throwable);
    }

    public KqException(int errCode, String errMsg, Throwable throwable) {
        super(errMsg, throwable);
        this.errCode = errCode;
        this.errMsg = errMsg;
        setCauseThrowable(throwable);
    }

    public KqException(ResponseCode responseCode) {
        super(responseCode.getMsg());
        this.errCode = responseCode.getCode();
        this.errMsg = responseCode.getMsg();
    }

    public int getErrCode() {
        return errCode;
    }

    public String getErrMsg() {
        if (!StringUtils.isBlank(this.errMsg)) {
            return errMsg;
        }
        if (this.causeThrowable != null) {
            return causeThrowable.getMessage();
        }
        return "";
    }

    public void setErrCode(int errCode) {
        this.errCode = errCode;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public void setCauseThrowable(Throwable throwable) {
        this.causeThrowable = getCauseThrowable(throwable);
    }

    private Throwable getCauseThrowable(Throwable t) {
        if (t.getCause() == null) {
            return t;
        }
        return getCauseThrowable(t.getCause());
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ErrCode:" + getErrCode() + ", ErrMsg:" + getErrMsg();
    }

    @Override
    public Integer getCode() {
        return getErrCode();
    }

    @Override
    public String getMsg() {
        return getErrMsg();
    }
}
